package com.sinodoggo.shitcloud.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sinodoggo.shitcloud.entity.Menu;
import com.sinodoggo.shitcloud.mapper.MenuMapper;
import com.sinodoggo.shitcloud.service.IMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author sinodoggo
 * @since 2022-11-21
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {
    @Resource
    private MenuMapper mapper;
    @Override
    public List<Menu> getAllMenus(String name) {
        QueryWrapper<Menu> wrapper = new QueryWrapper<>();
        if (!StrUtil.isBlank(name)) {
            wrapper.like("name", name);
        }
        final List<Menu> menuList = mapper.selectList(wrapper);
        // 找出所有父级菜单（顶级菜单）
        final List<Menu> parentMenuList = menuList.stream().filter(item -> item.getPid() == null).collect(Collectors.toList());
        // 为父级设置相应的子级菜单
        for (Menu parentMenu : parentMenuList) {
            final List<Menu> childMenu = menuList.stream().filter(item -> parentMenu.getId().equals(item.getPid())).collect(Collectors.toList());
            parentMenu.setChildren(childMenu);
        }
        return parentMenuList;
    }
}
